package cn.com.qtgl.sso.oidc.comp.security.impl;

import cn.com.qtgl.apis.builtin.comp.proxy.BuiltinProxy;
import cn.com.qtgl.apis.builtin.model.vo.IamTenant;
import cn.com.qtgl.sso.oidc.comp.security.TenantFactory;
import cn.com.qtgl.sso.oidc.comp.service.TokenService;
import cn.melonlib.authentication.model.entity.Tenant;
import org.hibernate.service.spi.ServiceException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Component
@ConditionalOnProperty(value = {"security.auth.tenant"},havingValue = "none",matchIfMissing = true)
public class DefaultTenantFactory implements TenantFactory {

    @Resource
    private TokenService tokenService;

    @Resource
    private BuiltinProxy builtin;
    @Override
    public Tenant getTenant() {
        try {
            Tenant tenant;
            try {
                tenant = builtin.tenantConfig();
                if(Objects.isNull(tenant)){
                    tenant = new Tenant();
                    tenant.setCode(tokenService.introspect(tokenService.getClientToken().getAccessToken()).getTenant());
                }
            }catch (Exception e){
                tenant = new Tenant();
                tenant.setCode(tokenService.introspect(tokenService.getClientToken().getAccessToken()).getTenant());
            }
            return tenant;
        }catch (Exception e){
            throw new ServiceException(e.getMessage(),e);
        }
    }
}
